package com.baizhi.controller;

import com.baizhi.dto.GroupDTO;
import com.baizhi.dto.GroupsDTO;
import com.baizhi.entity.Group;
import com.baizhi.feign.ClazzFeign;
import com.baizhi.po.ClazzsPO;
import com.baizhi.po.GroupPO;
import com.baizhi.po.GroupsPO;
import com.baizhi.service.GroupService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("groups")
public class GroupController {

    @Autowired
    private GroupService groupService;

    @Autowired
    private ClazzFeign clazzFeign;

    @GetMapping
    public List<GroupDTO> queryAll() {
        List<Group> groups = groupService.queryAll();
        List<GroupDTO> groupDTOS = new ArrayList<>();
        for (Group group : groups) {
            System.out.println("group = " + group);
            System.out.println("group.getClazzId() = " + group.getClazzId());
            ClazzsPO clazzsPO = clazzFeign.queryById(group.getClazzId());

            GroupDTO groupDTO = new GroupDTO(group.getId(), group.getName(), group.getCreatedate(), clazzsPO);
            groupDTOS.add(groupDTO);
        }
        return groupDTOS;
    }

    @PostMapping
    public GroupPO add(@RequestBody GroupsDTO groupsDTO) {
        Group add = groupService.add(groupsDTO);
        System.out.println("add = " + add);
        GroupPO groupPO = new GroupPO(add.getId(), add.getName(), add.getCreatedate());
        System.out.println("groupPO = " + groupPO);
        return groupPO;
    }

    @HystrixCommand(fallbackMethod = "HystrixQueryById")
    @GetMapping("{id}")
    public GroupsPO queryById(@PathVariable Long id) {
        Group group = groupService.queryById(id);
        GroupsPO groupsPO = new GroupsPO(group.getId(), group.getName());
        return groupsPO;
    }

    public GroupsPO HystrixQueryById(@PathVariable Long id) {
        GroupsPO groupsPO = new GroupsPO();
        groupsPO.setId(id);
        groupsPO.setName("服务不可用");
        return groupsPO;
    }
}
